<% environments = Environment.all %>
<div class="form-group">
  <%= form.label :name, 'Deploy Groups', class: 'col-lg-2 control-label' %>
  <div class=<%= "col-lg-#{2 + environments.length}" %> >
    <% if environments.length > 0 %>
      <%= hidden_field_tag "#{form.object_name}[deploy_group_ids][]" %>
      <table class="table table-condensed text-left deploy-groups">
        <thead>
        <tr>
          <% environments.each do |environment| %>
            <th>
              <%= label_tag do %>
                <%= check_box_tag '', nil, false, class: "env-toggle-all", data: {target: "#{environment.permalink}_checkbox" } %>
                <%= environment.name %>
              <% end %>
            </th>
          <% end %>
        </tr>
        </thead>
        <tbody>
        <% rows = environments.map { |e| [e, e.deploy_groups.sort_by(&:natural_order)] } %>
        <% rows.map { |_, dgs| dgs.size }.max.times do |index| %>
          <tr>
            <% rows.each do |environment, deploy_groups| %>
              <% if group = deploy_groups[index] %>
                <td>
                  <%= label_tag do %>
                    <% checked = form.object.deploy_group_ids.include?(group.id) %>
                    <%= check_box_tag "#{form.object_name}[deploy_group_ids][]", group.id, checked, class: "#{environment.permalink}_checkbox" %>
                    <%= group.name %>
                  <% end %>
                </td>
              <% else %>
                <td></td>
              <% end %>
            <% end %>
          </tr>
        <% end %>
        </tbody>
      </table>
    <% else %>
      <p>-- No Deploy Groups configured --</p>
    <% end %>
  </div>
</div>
